package com.uxsino.commons.utils.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PropXMLElement implements PropElement {

    private PropXMLDocument doc;

    private Element element;

    public PropXMLElement(PropXMLDocument doc, Element element) {
        this.doc = doc;
        this.element = element;
    }

    @Override
    public PropDocument getOwnerDoc() {
        return doc;
    }

    @Override
    public String getProp(String name) {
        return element.getAttribute(name);
    }

    @Override
    public List<PropElement> getElements(String name) {
        // NodeList nl = element.getElementsByTagName(name);
        // List<PropElement> elements = new ArrayList<>();
        //
        // for (int i = 0; i < nl.getLength(); i++) {
        // elements.add(new PropXMLElement(doc, (Element) nl.item(i)));
        // }
        // return elements;

        NodeList nl = element.getChildNodes();
        List<PropElement> elements = new ArrayList<>();

        for (int i = 0; i < nl.getLength(); i++) {
            if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element el = (Element) nl.item(i);
                if (el.getTagName().equals(name))
                    elements.add(new PropXMLElement(doc, (Element) nl.item(i)));
            }
        }
        return elements;

    }

    @Override
    public String getSourceLocation() {
        return (String) element.getUserData("ln");
    }

    @Override
    public List<PropElement> getChildElements(String childFieldName) {
        NodeList nl = element.getChildNodes();
        List<PropElement> elements = new ArrayList<>();

        for (int i = 0; i < nl.getLength(); i++) {
            if (nl.item(i).getNodeType() == Node.ELEMENT_NODE)
                elements.add(new PropXMLElement(doc, (Element) nl.item(i)));
        }
        return elements;

    }

    @Override
    public PropElement getFirstElement(String name, String fieldAsTag) {
        NodeList nl = element.getElementsByTagName(name);

        if (nl.getLength() > 0)
            return new PropXMLElement(doc, (Element) nl.item(0));
        return null;
    }

    @Override
    public String getTagName(String fieldAsTagName) {
        return element.getTagName();
    }

    @Override
    public Map<String, String> getProps() {
        HashMap<String, String> props = new HashMap<>();

        NamedNodeMap nm = element.getAttributes();
        if (nm == null)
            return props;
        for (int i = 0; i < nm.getLength(); i++) {
            Node n = nm.item(i);
            props.put(n.getNodeName(), n.getNodeValue());
        }
        return props;
    }

    @Override
    public String getText() {
        return element.getTextContent();
    }
}
